<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item v-if="!$route.query.id" :label="$t('基金名称')" prop="actTitle">
            <MainBodySelect
              v-model="form.fundId"
              :show-label="false"
              :parameters="'fund'"
              @change="changeFund"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input
              v-model="form.actTitle"
              :placeholder="$t('申请标题')"
              show-word-limit
              :maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('费用类型')" prop="typesFee">
            <el-select v-model="form.typesFee" :placeholder="$t('费用类型')">
              <el-option
                v-for="dict in typesFeeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发生时间')" prop="applyTime">
            <DatePicker
              v-model="form.applyTime"
              :placeholder="$t('发生时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('费用金额(元)')" prop="amountMoney">
            <Money v-model="form.amountMoney" unit="" :placeholder="$t('费用金额(元)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('类型')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('类型')">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('费用归属')" prop="costAttribution">
            <el-select v-model="form.costAttribution" :placeholder="$t('费用类型')">
              <el-option
                v-for="dict in costAttributionOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.costAttribution === 'deal'" :span="12">
          <el-form-item :label="$t('分摊项目')" prop="shareItem">
            <el-select v-model="form.shareItem" filterable :placeholder="$t('分摊项目')">
              <el-option
                v-for="dict in shareItemOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          v-if="form.payCompletionTime !== null && form.payCompletionTime !== '' && form.payCompletionTime !== undefined"
          :span="10"
        >
          <el-form-item :label="$t('付款完成时间')" prop="payCompletionTime">
            <el-date-picker
              v-model="form.payCompletionTime"
              clearable
              style="width: 200px"
              type="date"
              disabled
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              :placeholder="$t('付款完成时间')"
            />
          </el-form-item>
        </el-col>
        <el-col
          v-if="form.department !== null && form.department !== undefined && form.department !== ''"
          :span="2"
        >
          <br><br>
          <div class="el-form-item__content" style="margin-left: 120px;">
            <el-button @click="openProcessInfoForm(form.actId)">{{ $t('查看') }}</el-button>
          </div>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('费用明细')" prop="costsThat">
            <el-input
              v-model="form.costsThat"
              type="textarea"
              :placeholder="$t('费用明细')"
              maxlength="2000"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <FileTable
        :list.sync="form.fileList"
        data-type="fund_expense"
        :business-id="autoBusinessId($route.query.id, form)"
        :btn-show="!otherBtnHide"
      />

      <OnlinePreview ref="OnlinePreview" />
    </el-form>

    <el-dialog
      :visible.sync="infoOpen"
      :title="$t('流程详情')"
      :destroy-on-close="true"
      custom-class="dialogForm"
      style=" text-align: left;"
      append-to-body
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <ProcessInfoForm ref="processInfoForm" />
    </el-dialog>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!-- 使用流程：保存，保存并启动流程，取消 三个按钮-->
      <FormBtn v-if="useProcess" ref="formBtn" :bus-data="form" has-permi="fund:expense" :menu-key="menuKey" />
      <!--未使用流程：保存 取消按钮-->
      <save-btn v-if="!useProcess" has-permi="fund:expense" />
    </div>
  </div>
</template>

<script>
    import { saveFundExpense, getFundExpense } from '@/api/fund/expense/fundExpense'
    import { getFdSubjectList } from '@/api/fd/config/getTypeMain'
    import { getFundName } from '@/api/fund/fundBase'
    import { moneyFormat } from '@/utils/ruoyi'
    import { listDealInvestmentAll } from '@/api/deal/investment/dealInvestment.js'
    import ProcessInfoForm from '@/views/act/process/processInfoForm'
    import MainBodySelect from '@/components/MainBodySelect'
    import { getMenuProcess } from '@/api/act/process/wfMenuProcess'
    export default {
        components: {
          MainBodySelect,
          ProcessInfoForm
        },
        data() {
            return {
                // 菜单标识
                menuKey: 'fund_expense',
                // 是否配置了流程
                useProcess: false,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 表单参数
                form: {
                  // 费用明细
                  fundExpenseDetailList: [],
                  fileList: undefined
                },
                // 表单校验
                rules: {
                  typesFee: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  applyTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  amountMoney: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  shareItem: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  costAttribution: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  type: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                // 遮罩层
                loading: false,
                // 付款大类
                getFdSubjectList: [],
                // 上传文件
                fileList: undefined,
                infoOpen: false,
                typesFeeOptions: [],
                costAttributionOptions: [],
                // 是否显示上传按钮
                isShowUploadBtn: true,
                fymxLoading: false,
                deptOptions: [],
                // 上传路径
                uploadUrl: undefined,
                // 是否开启费用明细, 后台也需要去掉if
                whetherToOpenExpenseDetails: false,
                // 分摊项目
                shareItemOptions: [],
              // 现金流类型
              typeOptions: [],
              thatFundId: ''
            }
        },
        created() {
            // 查询是否配置了流程
            this.getUseProcess()
            // 付款大类
            getFdSubjectList('expense').then(response => {
              this.getFdSubjectList = this.changeSubjectList(response.data)
            })
            // 费用类型
            this.getDicts('fund_expense_type_fee').then(response => {
              this.typesFeeOptions = response.data
            })
            // 费用归属
            this.getDicts('fund_expense_cost_attribution').then(response => {
              this.costAttributionOptions = response.data
            })
            // 现金流类型
            this.getDicts('fund_expense_type').then(response => {
              this.typeOptions = response.data
            })
            this.$bus.$emit('async_done')
        },
        methods: {
            changeSubjectList(val) {
              const arr = []
              if (val.length !== 0) {
                val.forEach(item => {
                  const obj = {}
                  obj.value = item.value
                  obj.label = this.$t(item.label)
                if (item.children && item.children.length > 0) {
                    obj.children = this.changeSubjectList(item.children)
                  }
                  arr.push(obj)
                })
              }
              return arr
            },
            // 初始化数据
            init(data) {
              this.loading = true
              this.thatFundId = this.$route.query.id
              if (data != null && data.id !== undefined) {
                  getFundExpense(data.id).then(response => {
                    this.form = response.data
                    this.apportionmentItemSelect()
                    this.loading = false
                 })
              } else {
                this.reset()
                this.apportionmentItemSelect()
                this.loading = false
              }
            },
            changeFund() {
                this.thatFundId = this.form.fundId
                this.apportionmentItemSelect()
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                fundId: this.thatFundId,
                typesFee: undefined,
                applyTime: new Date(),
                department: undefined,
                amountMoney: undefined,
                costAttribution: undefined,
                shareItem: undefined,
                costsThat: undefined,
                payCompletionTime: undefined,
                actId: undefined,
                actStatus: undefined,
                fileList: undefined,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                  type: 'SJ',
                  whetherLp: 'N',
                fundExpenseDetailList: undefined,
                getFdSubjectList: []
                }
                try {
                  this.resetForm('form')
                } catch (e) {
                  console.log(e)
                }
            },
            // 分摊项目下拉
            apportionmentItemSelect() {
              this.shareItemOptions = []
              var fundId = this.form.fundId
              if (fundId === undefined || fundId === null || fundId === '') {
                fundId = this.thatFundId
              }
              listDealInvestmentAll({ investorId: fundId }).then(response => {
                console.log(response.data)
                if (response.data !== null && response.data !== undefined) {
                  response.data.forEach(item => {
                    const option = {
                      dictLabel: item.dealName,
                      dictValue: item.dealId
                    }
                    this.shareItemOptions.push(option)
                  })
                }
              })
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
                if (this.$parent.$parent.getStatisticalList !== undefined) {
                  this.$parent.$parent.getStatisticalList()
                }
                if (this.$parent.$parent.getChartData !== undefined) {
                  this.$parent.$parent.getChartData()
                }
                if (this.$parent.$parent.getChartDataByLp !== undefined) {
                  this.$parent.$parent.getChartDataByLp()
                }
            },
            /** 提交按钮 */
            submitForm: function(type) {
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                  // 验证数据
                  if (valid) {
                    if (this.form.costAttribution !== 'deal') {
                      this.form.shareItem = undefined
                    }
                    // 弹出遮罩层
                    this.loading = true

                    // 新增数据时 如果没有配置流程，则将审批状态设置为审批完成
                    if (!this.useProcess && !this.form.id) {
                      this.form.actStatus = 'W'
                    }

                    // 保存数据
                    saveFundExpense(this.form).then(response => {
                      if (response.code === 200) {
                        // 点击的按钮是保存并启动流程
                        if (type === 'process') {
                          // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                          this.form.id = response.data.id
                          // 启动流程
                          this.startProcess(response.data)
                          // 点击的仅保存
                        } else {
                          this.msgSuccess(this.$t('保存成功'))
                          // 关闭form页面
                          this.closeForm()
                        }
                        resolve()
                      } else {
                        this.msgError(response.msg)
                        this.loading = false
                        reject()
                      }
                    }).catch(() => {
                      this.loading = false
                    })
                  } else {
                    this.locationError(document)
                  }
                })
              })
            },
            // 启动流程
            startProcess: async function(data) {
               var fundName = await getFundName(this.thatFundId)
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = '「' + fundName + '」' + ': ' + this.form.actTitle + '(' + moneyFormat(data.amountMoney) + this.$t('元') + ')'
               // 业务表名
               processData.dataTable = 'fund_expense'
               // 业务ID
               processData.dataId = data.id
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/fund/expense/fundExpenseForm'
               processData.viewPath = '@/views/fund/expense/fundExpenseView'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = this.menuKey
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
            },
            // 预览附件
            onlinePreview(row) {
              this.$refs.OnlinePreview.onlinePreviewFile(row.id)
            },
            // 打开流程详情页面 查看OA 报销
            openProcessInfoForm(actId) {
              if (actId) {
                this.infoOpen = true
                this.$nextTick(() => {
                  this.$refs.processInfoForm.init({ actId: actId })
                })
              } else {
                this.msgError(this.$t('流程ID为空,不能查看流程信息'))
              }
            },
            // 获取是否使用流程
            getUseProcess() {
              getMenuProcess('fund_expense').then(response => {
                this.useProcess = !!response.data
              })
            }
        }
    }
</script>
